package cn.kt.mywxdemo.utils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


public class WordUtil {

    //随机笑话
    public static final String WORD_URL = "http://apis.juhe.cn/tyfy/query?key=%s";

    //申请接口的请求key
    // TODO: 您需要改为自己的请求key
    public static final String KEY = "a6c3cc5627b4d386c4645116890273ce";

    public static String getWords(String word) {
        //发送http请求的url
        String url = String.format(WORD_URL, KEY);
        final String response = HttpUtil.doPost(url, "word=" + word);
        System.out.println("接口返回：" + response);
        try {
            JSONObject jsonObject = JSONObject.fromObject(response);
            int error_code = jsonObject.getInt("error_code");
            if (error_code == 0) {
                System.out.println("调用接口成功");
                JSONObject result = jsonObject.getJSONObject("result");
                JSONArray words = result.getJSONArray("words");
                StringBuilder stringBuilder = new StringBuilder();
                words.stream().forEach(w -> stringBuilder.append(w + " "));
                System.out.println(stringBuilder);
                return stringBuilder.toString();
            } else {
                System.out.println("调用接口失败：" + jsonObject.getString("reason"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
